import 'dart:convert';

import 'package:crypto/crypto.dart';
import 'package:fluro/fluro.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:shenfuhui/entity/user_info_entity.dart';
import 'package:shenfuhui/routers/routers.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../config/config.dart';
import '../entity/user_info_entity.dart';
import '../http/api.dart';
import '../provider/userinfo_provider.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({Key? key}) : super(key: key);

  @override
  State<LoginPage> createState() => _LoginState();
}

class _LoginState extends State<LoginPage> {
  String _userName = "";
  String _passWord = "";

  ///
  /// 登录的逻辑
  ///
  login(Function onSucces) async {
    if (_userName.length < 11) {
      EasyLoading.showToast("请输入正确的手机号");
      return;
    }
    if (_passWord.length < 6) {
      EasyLoading.showToast("请输入6位以上密码");
      return;
    }

    var content = const Utf8Encoder().convert(_passWord);
    String md5pwd = "${md5.convert(content)}";
    dynamic result =
        await Api.login({'username': _userName, 'password': md5pwd});
    var jsonResult = jsonDecode(jsonEncode(result));
    if (jsonResult['code'] == 200) {
      //成功获得token,并保存起来
      SharedPreferences prefs = await SharedPreferences.getInstance();
      bool isOk = await prefs.setString('token', jsonResult['token']);
      // LogUtil.v(jsonResult['token']);
      if (isOk) {
        dynamic users = await Api.getUserinfo();
        Map<String, dynamic> resultUsers = Map.from(users);
        UserInfoEntity infoEntity = UserInfoEntity.fromJson(resultUsers);
        // onSucces.call();
        onSucces(infoEntity);
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        width: double.infinity,
        color: Config.colorBg,
        height: double.infinity,
        child: Stack(
          children: [
            // Image.asset(
            //   'assets/images/login_bg.png',
            //   width: double.infinity,
            //   height: 300.w,
            //   fit: BoxFit.fill,
            // ),
            Container(
              width: double.infinity,
              padding: EdgeInsets.symmetric(vertical: 50.w, horizontal: 38.w),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  //返回按钮
                  Container(
                    margin: EdgeInsets.only(top: 20.w),
                    child: InkWell(
                      onTap: () {
                        Routes.router.pop(context);
                      },
                      child: const Icon(Icons.close),
                    ),
                  ),
                  Container(
                    margin: EdgeInsets.only(left: 40.w, top: 60.w),
                    width: double.infinity,
                    child: Text(
                      Config.appName,
                      style: TextStyle(
                          fontSize: 60.sp, fontWeight: FontWeight.bold),
                    ),
                  ),
                  Container(
                    height: 88.w,
                    width: double.infinity,
                    margin: EdgeInsets.only(top: 80.w, left: 40.w, right: 40.w),
                    child: TextField(
                      keyboardType: TextInputType.text,
                      textAlign: TextAlign.justify,
                      maxLength: 20,
                      maxLines: 1,
                      onChanged: (value) {
                        setState(() {
                          _userName = value;
                        });
                      },
                      style:
                          TextStyle(fontSize: 26.sp, color: Config.colorText1),
                      decoration: InputDecoration(
                        hintText: '请输入用户名',
                        hintStyle: const TextStyle(color: Config.colorText3),
                        focusedBorder: OutlineInputBorder(
                          borderRadius: BorderRadius.all(
                            Radius.circular(44.w),
                          ),
                          borderSide:
                              const BorderSide(color: Config.colorDivider),
                        ),
                        enabledBorder: OutlineInputBorder(
                          borderRadius: BorderRadius.all(
                            Radius.circular(44.w),
                          ),
                          borderSide:
                              const BorderSide(color: Config.colorDivider),
                        ),
                        fillColor: Config.colorDivider,
                        filled: true,
                        counterText: '',
                        prefixIcon: Icon(
                          Icons.person,
                          color: Config.colorMain,
                          size: 33.w,
                        ),
                        contentPadding: EdgeInsets.symmetric(vertical: 10.w),
                      ),
                    ),
                  ),
                  Container(
                    height: 88.w,
                    width: double.infinity,
                    margin: EdgeInsets.only(top: 30.w, left: 40.w, right: 40.w),
                    child: TextField(
                      keyboardType: TextInputType.text,
                      textAlign: TextAlign.justify,
                      obscureText: true,
                      maxLength: 20,
                      maxLines: 1,
                      onChanged: (value) {
                        setState(() {
                          _passWord = value;
                        });
                      },
                      style:
                          TextStyle(fontSize: 26.sp, color: Config.colorText1),
                      decoration: InputDecoration(
                        hintText: '请输入密码',
                        counterText: '',
                        hintStyle: const TextStyle(color: Config.colorText3),
                        focusedBorder: OutlineInputBorder(
                          borderRadius: BorderRadius.all(
                            Radius.circular(44.w),
                          ),
                          borderSide:
                              const BorderSide(color: Config.colorDivider),
                        ),
                        enabledBorder: OutlineInputBorder(
                          borderRadius: BorderRadius.all(
                            Radius.circular(44.w),
                          ),
                          borderSide:
                              const BorderSide(color: Config.colorDivider),
                        ),
                        fillColor: Config.colorDivider,
                        filled: true,
                        prefixIcon: Icon(
                          Icons.lock_outline_rounded,
                          color: Config.colorMain,
                          size: 33.w,
                        ),
                        contentPadding: EdgeInsets.symmetric(vertical: 10.w),
                      ),
                    ),
                  ),
                  Container(
                    width: double.infinity,
                    height: 84.w,
                    margin: EdgeInsets.fromLTRB(40.w, 60.w, 40.w, 0),
                    child: ElevatedButton(
                      clipBehavior: Clip.antiAlias,
                      onPressed: () => login((UserInfoEntity infoEntity) {
                        Provider.of<UserInfoProvider>(context, listen: false)
                            .changeUserinfo(infoEntity);
                        Routes.router.pop(context);
                      }),
                      style: ElevatedButton.styleFrom(
                          shape: const StadiumBorder()),
                      child: const Text('登录'),
                    ),
                  ),
                  Container(
                    margin: EdgeInsets.only(right: 50.w, top: 20.w, left: 50.w),
                    width: double.infinity,
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        InkWell(
                          onTap: () {
                            Routes.navigateTo(context, Routes.mineFindPassword);
                          },
                          child: Text(
                            "找回密码",
                            textAlign: TextAlign.end,
                            style: TextStyle(
                              color: Config.colorMain,
                              fontSize: 26.sp,
                            ),
                          ),
                        ),
                        InkWell(
                          onTap: () {
                            Routes.navigateTo(context, Routes.register);
                          },
                          child: Text(
                            "新用户注册",
                            textAlign: TextAlign.end,
                            style: TextStyle(
                              color: Config.colorMain,
                              fontSize: 26.sp,
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}
